package com.orcsystem.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.orcsystem.common.to.SkuEsModel;
import com.orcsystem.search.config.OrcsystemElasticSearchConfig;
import com.orcsystem.search.constant.EsConstant;
import com.orcsystem.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @CreateData: 2020/11/17-15:25
 * Author   AiHongSen
 * 方法说明
 * SL 查询、DL 删除、UP 更新、IN 新增方法
 * ProductSaveServiceImpl->作用:
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;// 注入Bean容器里的es配置
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 先在 kibana 上创建 es 的map映射
        // 保存数据 index  批量宝UN bulk  BulkRequest bulkRequest, RequestOptions options EsConstant.PRODUCT_INDEX
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构建索引 product
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, OrcsystemElasticSearchConfig.COMMON_OPTIONS);
        // 是否有错误返回
        // TODO 如果有 批量错误
        boolean bool = bulk.hasFailures();
        List<String> list = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());
        log.error("批量上架错误：{}",list);
        return bool;
    }
}
